<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>登陆</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>登陆</h1>
    <form method="post" id="login-form" action="/login">
        <label>用户名</label><input type="text" name="username" value="sunny"/>
        <label>密码</label><input type="text" name="password" value="123456"/>
        <input type="submit" value="登陆" />
    </form>
    <script src="https://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.3.min.js"></script>
    <script>
        $(document).ready(function() {
            function getUrlParams() {
                var params = {};
                var paramPairs = [];
                var paramStr = location.search.substr(1);
                if (paramStr) {
                    paramPairs = paramStr.split('&');
                }
                var hashStr = location.hash;
                if (hashStr) {
                    var hashArray = hashStr.substr(1).split('&');
                    if (hashArray && hashArray.length > 0) {
                        Array.prototype.push.apply(paramPairs, hashArray);
                    }
                }
                for (var i = 0, len = paramPairs.length; i < len; i++) {
                    var pairNow = paramPairs[i];
                    if (pairNow.indexOf('=') != -1) {
                        var pairStr = pairNow.split('=');
                        params[pairStr[0]] = decodeURIComponent (pairStr[1]);
                    }
                }
                return params;
            };
            $('#login-form').submit(function() {
                var $this = $(this);

                $.post($this.attr('action'),$this.serialize()).then(function(result) {
                    if (result.code != 0) {
                        return alert(result.msg || '逻辑错误');
                    }
                    var urlParams = getUrlParams();
                    if (!urlParams.redirect) {
                        return alert('没有指定回调地址');
                    }
                    location.href = urlParams.redirect;
                }).fail(function() {
                    alert('网络错误');
                });
                return false;
            });
        });
    </script>
  </body>
</html>
